﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IOA.MES.DataAccess.Enum;

namespace IOA.MES.Business
{
    /// <summary>
    /// 包装条件配置（错误代码：114001）
    /// </summary>
    public class PackConditionMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public void Edit(VPackCondition model)
        {
            if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var entities = mesDb.PackConditions.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == model.WorkOrderNo && _.QLevelCondition == model.QLevelCondition && _.Valid).ToList();
                foreach (var entity in entities)
                {
                    mesDb.PackConditions.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                model.OrderNo = string.Empty;
                model.CreateTime = DateTime.Now;
                var newEntity = Mapper.Map<PackCondition>(model);
                mesDb.PackConditions.Add(newEntity);
            }
            else if (!string.IsNullOrWhiteSpace(model.OrderNo))
            {
                var entities = mesDb.PackConditions.AsNoTracking().Where(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.QLevelCondition == model.QLevelCondition && _.Valid).ToList();
                foreach (var entity in entities)
                {
                    mesDb.PackConditions.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                model.WorkOrderNo = string.Empty;
                model.CreateTime = DateTime.Now;
                var newEntity = Mapper.Map<PackCondition>(model);
                mesDb.PackConditions.Add(newEntity);
            }
            else
            {
                var entities = mesDb.PackConditions.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == "" && _.QLevelCondition == model.QLevelCondition && _.Valid).ToList();
                foreach (var entity in entities)
                {
                    mesDb.PackConditions.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                model.CreateTime = DateTime.Now;
                var newEntity = Mapper.Map<PackCondition>(model);
                mesDb.PackConditions.Add(newEntity);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 绑定工单产线
        /// </summary>
        /// <param name="vWorkOrder"></param>
        public void BindLine(VWorkOrder model)
        {
            var entity = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == model.WorkOrderNo && _.Valid);
            if (entity != null)
            {
                var lineIds = model.LineId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(_ => Convert.ToInt32(_)).ToList();
                var lines = !lineIds.Any() ? new List<AssemblyLine>()
                    : mesDb.AssemblyLines.AsNoTracking().Where(_ => lineIds.Contains(_.PkId) && _.Valid).ToList();

                mesDb.WorkOrders.Attach(entity);
                entity.LineId = string.Join(",", lines.Select(_ => _.PkId));
                entity.LineName = string.Join(",", lines.Select(_ => _.LineName));
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
                mesDb.SaveChanges();
            }
        }

        /// <summary>
        /// 获取打包规则
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <param name="qLevelCondition">等级分类</param>
        /// <returns>打包规则</returns>
        public VPackCondition GetPackCondition(string orderNo, string workOrderNo, QLevelCondition qLevelCondition)
        {
            PackCondition packCondition = null;
            if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                var workOrder = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == workOrderNo && _.Valid);
                if (workOrder == null)
                {
                    return null;
                }
                packCondition = mesDb.PackConditions.AsNoTracking().FirstOrDefault(_ => _.QLevelCondition == qLevelCondition && _.OrderNo == "" && _.WorkOrderNo == workOrderNo && _.Valid);
                if (packCondition == null)
                {
                    packCondition = mesDb.PackConditions.AsNoTracking().FirstOrDefault(_ => _.QLevelCondition == qLevelCondition && _.OrderNo == workOrder.OrderNo && _.WorkOrderNo == "" && _.Valid);
                }
            }
            else if (!string.IsNullOrWhiteSpace(orderNo))
            {
                packCondition = mesDb.PackConditions.AsNoTracking().FirstOrDefault(_ => _.QLevelCondition == qLevelCondition && _.OrderNo == orderNo && _.WorkOrderNo == "" && _.Valid);
            }
            else
            {
                packCondition = mesDb.PackConditions.AsNoTracking().FirstOrDefault(_ => _.QLevelCondition == qLevelCondition && _.OrderNo == "" && _.WorkOrderNo == "" && _.Valid);
            }

            return Mapper.Map<VPackCondition>(packCondition);
        }
    }
}
